const { BrowserWindow, app, globalShortcut } = require("electron");
const pie = require("puppeteer-in-electron")
const puppeteer = require("puppeteer-core");
const { clipboard } = require('electron')
var remarkLock = true

clipboard.writeText("")
var text = clipboard.readText()

function listenClipboard(fn) {
  var timer = setInterval(() => {
    if(clipboard.readText() !== text) {
      clearInterval(timer)
      fn()
    }
  }, 100)
}

async function waitLogin(page) {
  console.log("进入登陆页面")
  const URL = "https://login.taobao.com/member/login.jhtml?spm=2013.1.754894437.1.70284b006yzwMe&f=top&redirectURL=https%3A%2F%2Fitem.taobao.com%2Fitem.htm%3Fspm%3Da1z10.3-c-s.w4002-22455284423.21.60867522p2RDie%26id%3D619096144951"
  await page.goto(URL)

  console.log("等待用户登陆")
  return page.waitForNavigation({ timeout: 0 })
}

async function buy(page) {
  // 按钮选择器
  const buy_button = ".J_LinkBuy"
  const submit_order_btn = "#submitOrderPC_1 .go-btn"

  // 选配色
  await page.evaluate(() => {
    [...document.querySelectorAll('[data-property="颜色分类"] li')]
      .find(element => {
        const text = element.textContent.toLocaleLowerCase()
        
        return /(eva|wisteria|chestnut)/.test(text)
      })
      .click()
  });

  // 点击购买
  await page.waitFor(buy_button)
  await page.click(buy_button)

  // 点击提交
  if(!remarkLock) {
    await page.waitFor(submit_order_btn)
    await page.click(submit_order_btn)
  }
  else {
    await page.focus('[data-halo-type="textArea"] textarea')
    // await page.evaluate(() => {
    //   var elem = document.querySelector('[data-halo-type="textArea"] textarea')
    //   elem.click()
    // })
  }
}

const main = async () => {
  await pie.initialize(app);
  const browser = await pie.connect(app, puppeteer);
 
  const window = new BrowserWindow();
 
  const page = await pie.getPage(browser, window);
  
  setTimeout(async () => {
    console.log(`剪切板发生变化：${clipboard.readText()}`)
    await waitLogin(page)
  })

  listenClipboard(async () => {
    const product_url = clipboard.readText()
    
    if(product_url.includes('http')) {
      await page.goto(product_url)
      await buy(page)
    }
  })
};
 
main();